<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: sap<songaiping@hrbjjhh.com>
// +----------------------------------------------------------------------------
/**
 +------------------------------------------------------------------------------
* 商品团购模型
+------------------------------------------------------------------------------
* @version   1.0
* @since 2015-12-1
+------------------------------------------------------------------------------
*/
namespace Home\Model;

class ShopGroupModel {

    public $error;//记录最后一次错误信息
    
    /**
     * @todo 处理团购列表数据
     * @param array $list
     * @author sap
     * @since 2015-12-1
     */
    public function handleShopList($list=array()){
        //基础判断
        $list = (array)$list;
        if(empty($list)){
            $this->error = '数据传输中丢失，请重试';
            return false;
        }
        //参团人数
        $shop_group_id_arr = array_unique(array_column($list,'shop_group_id'));
        $group_count = M('ShopGroupTeamCustomer')->where(array('shop_group_id'=>array('in',$shop_group_id_arr)))->field('shop_group_id,count(*) as total')->group('shop_group_id')->select();
        
        $date = array();
        if(!empty($group_count)){
            foreach ($group_count as $key=>$val){
                $data[$val['shop_group_id']] = $val['total'];
            }
        }
        foreach ($list as $k=>$v){
            $list[$k]['group_count'] = isset($data[$v['shop_group_id']]) ? $data[$v['shop_group_id']] : 0;
            $list[$k]['goods_name'] = msubstr($v['goods_name'],0,26);
            $list[$k]['goods_introduction'] = msubstr($v['goods_introduction'],0,100);
            $list[$k]['goods_link'] = U('/Shop/goodsGroupInfo',array('goods_id'=>$v['goods_id']));
            $pic = getPictureThumb($v['shop_group_pic_id'],100,100);
            $list[$k]['goods_thumb'] = !empty($pic) ? $pic : '/Public/Home/common/img/jjhh1-1.jpg';           
        }
        return $list;
    }
    
    /**
     * @todo 团购详情
     * @author sap
     * @since 2015-12-1
     */
    public function shopGroupInfo(){
        //基础数据
        $goods_id = (int)I('goods_id');//商品ID
        $team_id = (int)I('team_id');//团队ID
        $info = $this->goodsGroupInfo($goods_id);//团购商品基础信息
        if(empty($info)){
            $this->error = $this->getError();
            return false;
        }
        //参与本团人员
        if($team_id > 0){
            $shop_group_customer_num = $this->shopGroupCustomerNum(array('team_id'=>$team_id,'shop_group_id'=>$info['shop_group_id']));
        }
        $info['shop_group_customer_num'] = isset($shop_group_customer_num) ? $shop_group_customer_num : 0;
        $info['team_id'] = $team_id;
        /**
         * 按钮状态信息
         */
        //判断是否登陆
        if(UID == 0){
            $info['but_status'] = 0;//未登陆显示“登陆”按钮
            return $info;
        }
        //判断是否参加过本次团购
        $is_group = $this->shopGroupCustomerInfo(array('customer_id'=>UID,'shop_group_id'=>$info['shop_group_id']));
        //未参加过本次团购
        if(empty($is_group)){
            if($info['shop_group_stock'] < 1){
                $info['but_status'] = 7;//库存为0时，显示“缺货”按钮
                return $info;
            }
            if($team_id == 0){
                $info['but_status'] = 1;//没有链接分享的团队ID（team_id），显示“我要开团”按钮
                return $info;
            }
            //未参加过本次团购,并且有链接分享的团队ID（team_id），判断团队人员是否已满，
            if($shop_group_customer_num >= $info['shop_group_customer_number']){
                $info['but_status'] = 2;//已满显示“已满”和“我要开团”按钮
            }elseif($shop_group_customer_num == 0){
                $info['but_status'] = 1;//有链接分享的团队ID（team_id），但是team在本产品中没有人时，显示“我要开团”按钮
            }else{
                $info['but_status'] = 3;//未满显示“我要入团”按钮
            }
            return $info;
        }
        if($team_id != $is_group['team_id']){
            $info['team_id'] = $is_group['team_id'];
            //team_id信息有错时，读正确信息
            $shop_group_customer_num = $this->shopGroupCustomerNum(array('team_id'=>$is_group['team_id'],'shop_group_id'=>$info['shop_group_id']));
            $info['shop_group_customer_num'] = isset($shop_group_customer_num) ? $shop_group_customer_num : 0;
        }
        //参加过本次团购，判断是否有订单信息，判断团队人员是否已满
//         if($is_group['order_id'] != 0){
//             $info['but_status'] = 6;//有订单信息，显示“已购买”按钮
//             return $info;
//         }
//        $team_customer_num = $this->shopGroupCustomerNum(array('team_id'=>$is_group['team_id']));
        if($shop_group_customer_num >= $info['shop_group_customer_number']){
            $info['but_status'] = 4;//已满显示“购买”按钮
        }else{
            $info['but_status'] = 5;//未满显示“分享”按钮
        }
        return $info;
    }
    
    /**
     * @todo 开团
     * @author sap
     * @since 2015-12-2
     */
    public function goodsGroupOpen(){
        $goods_id = (int)I('goods_id');
        if($goods_id == 0){
            $this->error = '请正确操作';
            return false;
        }
        //获取商品团购信息,商品ID
        $obj = D('Admin/ShopGroup');
        $info = $obj->getGroupGoodsInfo(array('goods_id'=>$goods_id));
        if(empty($info)){
            $this->error = $obj->getError();
            return false;
        }
        //团购库存不得小于开团人数
        if($info['shop_group_stock'] < $info['shop_group_customer_number']){
            $this->error = '团购库存不足开团';
            return false;
        }
        //判断是否参加过本次团购
        $is_group = $this->shopGroupCustomerInfo(array('customer_id'=>UID,'shop_group_id'=>$info['shop_group_id']));
        if(!empty($is_group)){
            $this->error = '已经参加过本次团购';
            return false;
        }
        //操作数据库
        M()->startTrans();
        if(M('ShopGroup')->where(array('shop_group_id'=>$info['shop_group_id']))->setDec('shop_group_stock',$info['shop_group_customer_number']) === false){
            M()->rollback();
            $this->error = '操作失败';
            return false;
        }
        $data_team['goods_id'] = $info['goods_id'];
        $data_team['shop_group_id'] = $info['shop_group_id'];
        $data_team['create_by'] = UID;
        $data_team['create_time'] = NOW_TIME;
        if($info['shop_group_customer_number'] == 1){
            $data_team['order_type'] = 1;
        }
        $team_id = M('ShopGroupTeam')->add($data_team);
        if(empty($team_id)){
            M()->rollback();
            $this->error = '操作失败';
            return false;
        }
        $data_customer['shop_group_id'] = $info['shop_group_id'];
        $data_customer['goods_id'] = $info['goods_id'];
        $data_customer['team_id'] = $team_id;
        $data_customer['customer_id'] = UID;
        if(M('ShopGroupTeamCustomer')->add($data_customer) === false){
            M()->rollback();
            $this->error = '操作失败';
            return false;
        }
        M()->commit();
        return $team_id;
    }
    
    /**
     * @todo 入团
     * @author sap
     * @since 2015-12-2
     */
    public function goodsGroupIn(){
        $team_id = (int)I('team_id');//团队ID
        $goods_id = (int)I('goods_id');//商品ID

        if($team_id == 0 || $goods_id == 0){
            
            $this->error = '请正确操作'.$team_id.'/'.$goods_id;
            return false;
        }
        //获取商品团购信息,商品ID
        $obj = D('Admin/ShopGroup');
        $info = $obj->getGroupGoodsInfo(array('goods_id'=>$goods_id));
        if(empty($info)){
            $this->error = $obj->getError();
            return false;
        }
        $team_customer_num = $this->shopGroupCustomerNum(array('team_id'=>$team_id,'shop_group_id'=>$info['shop_group_id']));//判断团队人员是否已满，
        if($team_customer_num == 0 || $team_customer_num >= $info['shop_group_customer_number']){
            $this->error = '本团已满';
            return false;
        }
        //判断是否参加过本次团购
        $is_group = $this->shopGroupCustomerInfo(array('customer_id'=>UID,'shop_group_id'=>$info['shop_group_id']));
        if(!empty($is_group)){
            $this->error = '已经参加过本次团购';
            return false;
        }
        //操作数据库
        M()->startTrans();
        if($team_customer_num + 1 == $info['shop_group_customer_number']){
            $data_team['team_id'] = $team_id;
            $data_team['order_type'] = 1;//可支付
            if(M('ShopGroupTeam')->save($data_team) === false){
                M()->rollback();
                $this->error = '操作失败';
                return false;
            }
        }
        $data_customer['shop_group_id'] = $info['shop_group_id'];
        $data_customer['goods_id'] = $info['goods_id'];
        $data_customer['team_id'] = $team_id;
        $data_customer['customer_id'] = UID;
        if(M('ShopGroupTeamCustomer')->add($data_customer) === false){
            M()->rollback();
            $this->error = '操作失败';
            return false;
        }
        M()->commit();
        return true;
    }
    
    /**
     * @todo 团购商品购买
     * @author sap
     * @since 2015-12-3
     */
    public function goodsGroupBuy(){
        $goods_id = (int)I('goods_id');
        if($goods_id == 0){
            $this->error = '请正确操作';
            return false;
        }
        //获取商品团购信息,商品ID
        $obj = D('Admin/ShopGroup');
        $info = $obj->getGroupGoodsInfo(array('goods_id'=>$goods_id));
        if(empty($info)){
            $this->error = $obj->getError();
            return false;
        }
        //判断是否参加过本次团购
        $is_group = $this->shopGroupCustomerInfo(array('customer_id'=>UID,'shop_group_id'=>$info['shop_group_id']));
        if(empty($is_group)){
            $this->error = '还没参加过本商品本次团购哦';
            return false;
        }
        if($is_group['order_id'] > 0){
            return (int)$is_group['order_id'];
        }
//         if($is_group['order_id'] > 0){
//             $this->error = '已经购买，不可重复购买';
//             return false;
//         }
        //判断是否可以支付
//         $is_team = $this->shopGroupTeamInfo(array('team_id'=>$is_group['team_id']));
//         if($is_team['order_type'] != 1){
//             $this->error = '该团队还不可以支付哦，赶快分享吧';
//             return false;
//         }
        $team_customer_num = $this->shopGroupCustomerNum(array('team_id'=>$is_group['team_id']));
        if($team_customer_num < $info['shop_group_customer_number']){
            $this->error = '该团队还不可以支付哦，赶快分享吧';
            return false;
        }
        //下单接口，读海哥，传$goods_id,返回$order_id
        $obj_ordery = D('Home/ShopOrder');
        $order_id = $obj_ordery->buyGoods($goods_id,UID,3);
        if(empty($order_id)){
            $this->error = $obj_ordery->getError();
            return false;
        }
        //操作数据库
        $obj = M('ShopGroupTeamCustomer');
        $map['team_id'] = $is_group['team_id'];
        $map['goods_id'] = $goods_id;
        $map['customer_id'] = UID;
        $data['order_id'] = $order_id;
        if($obj->where($map)->save($data) === false){
            $this->error = $obj->getDbError();
            return false;
        }
        return $order_id;
    }
    
    /**
     * @todo 团购商品基础信息
     * @author sap
     * @since 2015-12-2
     */
    public function goodsGroupInfo($goods_id=0){
        $goods_id = (int)$goods_id;
        if($goods_id == 0){
            $this->error = '请正确操作';
            return false;
        }
        $obj = D('Admin/ShopGroup');
        //获取商品详细信息,商品ID，上架，团购状态
        $goods_info = $obj->getGoodsInfo(array('goods_id'=>$goods_id,'status'=>'1','goods_type'=>'2'),'goods_id,goods_name,market_price,goods_deposit,goods_content,goods_introduction,goods_unit');
        if(empty($goods_info)){
            $this->error = '无商品信息';
            return false;
        }
        //手机端懒加载商品内容
        $goods_info['goods_content'] = preg_replace('/<img([\s\S]+?)src\s*=([\s\S]+?)>/i', "<img$1data-echo=$2 width='100%' src='' />", $goods_info['goods_content']);
        //获取商品团购信息,商品ID
        $group_info = $obj->getGroupGoodsInfo(array('goods_id'=>$goods_id),'shop_group_id,goods_id,shop_group_customer_number,shop_group_price,shop_group_stock,shop_group_pic_id');
        if(empty($group_info)){
            $this->error = '无商品团购信息';
            return false;
        }
        $info = array_merge($goods_info,$group_info);//合并商品信息
        return $info;
    }
    
    /**
     * @todo 参团人数
     * @author sap
     * @since 2015-12-2
     */
    public function shopGroupCustomerNum($where=array()){
        return M('ShopGroupTeamCustomer')->where($where)->count();
    }
    
    /**
     * @todo 参团人员表，单条查询
     * @author sap
     * @since 2015-12-2
     */
    public function shopGroupCustomerInfo($where=array()){
        return M('ShopGroupTeamCustomer')->where($where)->find();
    }
    
    /**
     * @todo 参团团队信息，单条查询
     * @author sap
     * @since 2015-12-3
     */
    public function shopGroupTeamInfo($where=array()){
        return M('ShopGroupTeam')->where($where)->find();
    }
    
    /**
     * @todo 返回最后一次错误信息
     * @return string
     * @author PHP@妖孽 <dino_ma@163.com>
     */
    public function getError(){
        return $this->error;
    }
}
